<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn">按钮</button>
  <button id="btn2">按钮</button>
  <script>
    // 通过 websocket 完成前后端通信
    // 1. 创建ws实例，建立连接
    const ws = new WebSocket("wss://javascript.info/article/websocket/demo/hello")
    // 2. 监听连接成功
    ws.onopen = function (){
      console.log('连接成功')  
    }
    // 3. 给服务器发消息
     document.querySelector('#btn').addEventListener('click',function(){
      ws.send('你好')
     })
    // 4. 接收服务器发的消息
    ws.onmessage = (event)=>{
       console.log(event.data)   
    }
    // 5. 关闭连接
    document.querySelector('#btn2').addEventListener('click',function(){
      ws.close()
    })
    // 6. 监听通信关闭
    ws.onclose = ()=>{
      console.log('连接关闭')
      
    }
  </script>
</body>
</html>